<?php

declare(strict_types=1);

namespace app\api\controller;

use app\admin\model\HomeUser;
use app\common\controller\ApiController;
use Firebase\JWT\JWT;
use PhpOffice\PhpSpreadsheet\Calculation\Information\Value;
use think\facade\Cache;
use think\facade\Validate;
use think\facade\View;
use think\Request;
use think\validate\ValidateRule;

class Auth extends ApiController
{
    // algorithms
    public const AUTH_ALGORITHM = 'HS256';

    protected $noTokenVerifyAction = ['buildToken', 'requestCaptcha'];

    public function requestCaptcha()
    {
    }

    public function buildToken()
    {

        $validate = Validate::rule('username', ValidateRule::isRequire())
            ->rule('password', ValidateRule::isRequire());

        $post_data = $this->requestData($validate);

        $model_user = HomeUser::where("username", $post_data['username'])->find();

        if (empty($model_user)) {
            return $this->returnMessage('用户不存在');
        }

        if (password($post_data['password'], $model_user->password_salt) != $model_user->password) {
            return $this->returnMessage('登陆失败，用户密码错误');
        }

        $api_key = sysconfig('site', 'api_key');

        $auth_info['username'] =  $model_user->username;

        $auth_info['expire_time']  = time() + 86400 * 3;

        $jwt = JWT::encode($auth_info, $api_key, Auth::AUTH_ALGORITHM);

        return $this->returnMessage([
            'access_token' => $jwt,
        ]);
    }

    public function refreshToken()
    {
        $api_key = sysconfig('site', 'api_key');

        $auth_info['username'] =  $this->modelUser->username;

        $auth_info['expire_time']  = time() + 86400 * 3;

        $jwt = JWT::encode($auth_info, $api_key, Auth::AUTH_ALGORITHM);

        return $this->returnMessage([
            'access_token' => $jwt,
        ]);
    }

    public function userinfo()
    {
        return $this->returnMessage($this->modelUser);
    }
}
